<template>
  <div class="component">
    <el-container>
      <el-aside style="width: 26%;border:1px solid #ddd;border-radius: 10px;margin-right: 10px;">
        <el-table :data="components" @row-click="handleRowClick" style="width: 100%;height: 100%;padding: 10px;" :fit="false">
          <el-table-column prop="name" width="400">
            <template #default="scope">
              <div>
                <img :src="getCompsIcon(scope.row.type)" style="vertical-align: middle; padding-right: 4px;"/>
                <span>{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" width="60">
            <template #default="scope">
              <img v-if="scope.row.status==0" src="../assets/correct.png">
              <img v-if="scope.row.status==1" src="../assets/waiting.png">
              <img v-if="scope.row.status==2" src="../assets/wrong.png">
            </template>
          </el-table-column>
        </el-table>
      </el-aside>
      <el-main style="height: 100%;padding-top: 0px;padding-right: 0px;">
          <el-tabs style="height: 100%;">
            <el-tab-pane label="User">
              <template #label>
                <el-tooltip content="文本视图" placement="top">
                  <img src="../assets/board.png"/>
                </el-tooltip>
              </template>
              <div style="display: flex; margin-right: 10px;height: 95%;">
                <el-input type="textarea" v-model="policy_json_str" placeholder="请输入 JSON 数据" />
                <div style="padding-left: 15px;">
                  <el-button type="text" style="padding-top: 0px;" @click="formatJSON">
                    <template #icon>
                      <el-tooltip content="格式化JSON" placement="top">
                        <img src="../assets/json.png"/>
                      </el-tooltip>
                    </template>
                  </el-button>
                </div>
              </div>
              <div style="height: 5%;padding-top: 10px">
                <el-button type="primary" @click="clearBoard">清除</el-button>
                <el-button type="primary" @click="submitPolicyJson">提交</el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="Config">
              <template #label>
                <el-tooltip content="表单视图" placement="top">
                  <img src="../assets/form.png"/>
                </el-tooltip>
              </template>
              <div style="height:100%;background-color:white;border: 1px solid #ddd;border-radius: 10px;overflow: auto;">
                <div style="padding: 10px">
                  <div>
                    <el-button type="primary" @click="addNode">添加</el-button>
                    <el-button type="success" @click="submitPolicy">提交</el-button>
                  </div>
                  <div style="padding-top: 10px;padding-bottom: 10px;display: flex;">
                    <el-text class="mx-1" style="padding-left: 10px;">
                      当前组件：
                      <img :src="getCompsIcon(curr_comp_type)" v-if="curr_comp_type.length>0" style="vertical-align: middle; padding-right: 4px;"/>
                      {{ policy.comp }}
                    </el-text>
                  </div>
                  <div>
                    <el-text class="mx-1">集群名称：</el-text>
                    <el-input class="el-node-input" v-model="policy.name" placeholder="cluster name" clearable />
                    <el-text class="mx-1" style="padding-left: 10px;">集群模式：</el-text>
                    <el-select class="el-node-input" v-model="policy.mode" placeholder="select">
                        <el-option v-for="mode in modes" :key="mode" :label="mode" @click="onModeChanged(mode)"/>
                    </el-select>
                  </div>
                  <div :index="index" v-for="(node,index) in policy.nodes" :key="index" style="padding: 5px;">
                    <el-button type="danger" @click="delNode(index)"> 删除 </el-button>
                      <el-input class="el-node-input" v-model="node.addr" placeholder="ip" clearable />
                      <el-input class="el-node-input" v-model="node.hostname" placeholder="hostname" clearable />
                      <el-input class="el-node-input" v-model="node.auths" placeholder="user/password" clearable />
                      <div style="display: flex;">
                        <div style="padding-top: 5px" v-for="(role,roleIndex) in node.roles" :key="roleIndex">
                          <el-select style="padding-right: 5px;" v-model="node.roles[roleIndex]" placeholder="select">
                            <el-option v-for="compRole in compRoles" :key="compRole" :label="compRole" @click="onRoleChanged(index,roleIndex,compRole)"/>
                          </el-select>
                          <el-button type="text" style="padding-right:5px" @click="delRole(index,roleIndex)">
                            <template #icon>
                              <el-tooltip content="delete role" placement="top">
                                <img src="../assets/minus.png"/>
                              </el-tooltip>
                            </template>
                          </el-button>
                        </div>
                      </div>
                      <el-button type="text" style="padding-left:5px" @click="addRole(index)">
                        <template #icon>
                          <el-tooltip content="add role" placement="top">
                            <img src="../assets/add.png"/>
                          </el-tooltip>
                        </template>
                      </el-button>
                  </div>
                </div>
                <div style="padding-left: 10px;padding-right:10px;height: 500px">
                  <el-input type="textarea" v-model="env_str" />
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import {ref } from 'vue'
import config from '@/configs/config'
export default {
  name: "ComponentView",
  setup(){
    const domain = ref("http://"+config.server.ip+":"+config.server.port)
    const policy = ref({"comp":"","name":"","type":"","mode":"","nodes":[],"config":{}})
    const policy_json_str = ref("")
    const policy_json = ref("")
    const curr_comp_type = ref("")
    const env_str = ref("")
    const components = ref([])
    const modes = ref([])
    const compRoles = ref([])
    const getComps=()=>{
      fetch(domain.value+"/components/getcomponents")
      .then(response=>response.json())
      .then(data=>{
        components.value = JSON.parse(data.result)
      })
    }

    const getCompModes=()=>{
      fetch(domain.value+"/components/getcompmodes?comp="+policy.value.comp)
      .then(response=>response.json())
      .then(data=>{
        modes.value = data.result.split(",")
      })
    }

    const getCompRoles=()=>{
      fetch(domain.value+"/components/getcomproles?comp="+policy.value.comp +"&mode="+policy.value.mode)
      .then(response=>response.json())
      .then(data=>{
        compRoles.value = data.result.split(",")
      })
    }

    const getCompConfigs=()=>{
      fetch(domain.value+"/components/getcompconfigs?comp="+policy.value.comp +"&mode="+policy.value.mode)
      .then(response=>response.json())
      .then(data=>{
        env_str.value = data.result
      })
    }

    const handleRowClick = (row)=>{
      policy.value.comp = row.name
      policy.value.type = row.type
      curr_comp_type.value = row.type
      getCompModes()
    }

    const onModeChanged =(mode)=>{
      policy.value.mode = mode
      getCompRoles()
      getCompConfigs()
    }
    

    const onRoleChanged=(nodeIndex,roleIndex,roleSelected)=>{
      policy.value.nodes[nodeIndex].roles[roleIndex] = roleSelected
    }

    const addNode = ()=>{
      var node = {"addr":"","hostname":"","auths":"","roles":[]}
      policy.value.nodes.push(node)
    }


    const delNode=(index)=>{
      policy.value.nodes.splice(index,1)
    }

    const addRole=(nodeIndex)=>{
      policy.value.nodes[nodeIndex]["roles"].push("")
    }

    const delRole=(nodeIndex,roleIndex)=>{
      policy.value.nodes[nodeIndex].roles.splice(roleIndex,1)
    }

    const getCompsIcon=(filename)=>{
      return require(`@/assets/${filename}.png`)
    }

    const submitPolicy = ()=>{
      const lines = env_str.value.split("\n")
      lines.forEach(line=>{
        if(line!=""){
          const parts = line.trim().split("=")
          let key = parts[0].trim()
          let val = parts[1].trim()
          policy.value.config[key]=val
        }
      })
      fetch(domain.value+"/components/policysubmit",{
        method:"POST",
        headers:{
          "Content-Type":"application/json",
        },
        body:JSON.stringify(policy.value)
      })
      .then(response=>response.json())
      .then(data=>{
        alert(data.msg)
      })
    }


    const submitPolicyJson=()=>{
      if(policy_json_str.value==""){
        alert("内容不能为空")
        return
      }
      policy_json.value = JSON.parse(policy_json_str.value)
      fetch(domain.value+"/components/policysubmit",{
        method:"POST",
        headers:{
          "Content-Type":"application/json",
        },
        body:JSON.stringify(policy_json.value)
      })
      .then(response=>response.json())
      .then(data=>{
        console.log(data.msg)
      })
    }

    const formatJSON = () => {
      try{
        const policy_parsed = JSON.parse(policy_json_str.value)
        policy_json_str.value = JSON.stringify(policy_parsed,null,2)
      }catch(error){
        alert("无效的Json数据")
      }
      
    }

    const clearBoard = () => {
      policy_json_str.value = ""
    }

    return{
      domain,
      policy,
      policy_json_str,
      policy_json,
      curr_comp_type,
      env_str,
      components,
      modes,
      compRoles,
      getCompsIcon,
      getComps,
      handleRowClick,
      onModeChanged,
      getCompModes,
      getCompRoles,
      getCompConfigs,
      onRoleChanged,
      addNode,
      delNode,
      addRole,
      delRole,
      submitPolicy,
      submitPolicyJson,
      formatJSON,
      clearBoard
    }
  },
  
  mounted(){
    this.getComps()
  },

}
</script>

<style lang="scss">
.component {
  height: 100%;
}

.el-aside{
  height: 100%;
}

.el-container{
  height: 100%;
}

.el-container .el-row-container{
  display:block;
  padding-bottom: 10px;
}


.el-tabs {
  width: 100%;
}

.el-tabs > .el-tabs__header {
  height: 4%;
}

.el-tabs > .el-tabs__content {
  height: 96%;
}

.el-textarea {
  height: 100%;
}

.el-tabs__item {
  padding: 0;
  margin-right: 10px;
}

.el-textarea__inner {
  height: 100%;
}

.el-tab-pane {
 height: 100%;
}

.el-node-input{
  width: 250px;
  padding-left: 10px;
}

.el-role-collapse{
  font-size: medium;
}

.el-collapse-item__header {
  font-size: 15px;
}

</style>


